package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Component;

/**
 * @Author: huanggaotao
 * @Description:
 * @Date: Created in 9:38 2021/4/26
 * @Modified By:
 */
/**
 * 当前项目表示一个认证授权中心
 *
 * */

@Component
//开启认证授权中心 serve端
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.authenticationManager()
                .userDetailsService()

    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单提交  检查accessToken是否有效的情况下 权限要放开
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("permitAll()");
    }


    /**
     * 分配我们的appid和appkey  clientid  clientkey
      * */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        //这段代码正常情况下是去查查数据库的
        clients.inMemory()
                // appid
                .withClient("mayikt")
                // appsecret 密钥
                .secret(passwordEncoder.encode("mayikt_secret"))
                // 授权码
                .authorizedGrantTypes("authorization_code")
                // 作用域  下面表示 所有接口都可以访问
                .scopes("all")
                // 资源的id
                .resourceIds("mayikt_resource")
                // 回调地址   用户选择授权之后，跳转到该地址传递code授权码
                .redirectUris("http://www.baidu.com/callback");

    }
}
